import store from '@/store'

function doHasPermission(el, binding) {
  const { value } = binding
  if (!store.getters.permissionMap[value]) {
    el.parentNode && el.parentNode.removeChild(el)
  }
}

function doHasRole(el, binding) {
  const { value } = binding
  if (typeof value === 'string') {
    if (!store.getters.roleMap[value]) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else if (typeof value === 'object') {
    let has = false
    for (const v of value) {
      if (store.getters.roleMap[v]) {
        has = true
        break
      }
    }
    if (!has) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}

function doIsDistrictAdmin(el, binding) {
  const { value } = binding

  // 两个条件可以二选一成立，例如用于这种场合：管理员或者自己的可以编辑
  if (!value && !store.getters.roleMap['district_admin']) {
    el.parentNode && el.parentNode.removeChild(el)
  }
}

const hasPermission = {
  inserted(el, binding) {
    doHasPermission(el, binding)
  },
  update(el, binding) {
    doHasPermission(el, binding)
  }
}

const hasRole = {
  inserted(el, binding) {
    doHasRole(el, binding)
  },
  update(el, binding) {
    doHasRole(el, binding)
  }
}

const isDistrictAdmin = {
  inserted(el, binding) {
    doIsDistrictAdmin(el, binding)
  },
  update(el, binding) {
    doIsDistrictAdmin(el, binding)
  }
}

export { hasPermission, hasRole, isDistrictAdmin }
